<template>
  <div class="view-player">
    <article>
      <h2>你的token是</h2>
      <p class="token-show">{{ loginToken }}</p>
      <Button
        class="register-back-btn"
        type="primary"
        @click="handleBackClicked"
      >
        <Icon type="ios-go"></Icon>
        返回</Button
      >
    </article>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from '@/plugins/class-component-hooks'
import { playerModule } from '../store'
import { VueApolloQueryDefinition } from 'vue-apollo/types/options'
import { PlayerQuery } from '../types'
import { Watch } from 'vue-property-decorator'
import { gqlErrorHandler } from '../util/errorHandler'

@Component({
  components: {}
})
export default class PlayerView extends Vue {
  @Prop({ default: '/roomlist' }) prevPath!: string

  private player!: PlayerQuery['player']
  private loginToken: string = ''

  handleBackClicked() {
    this.$router.push({ path: this.prevPath })
  }

  @Watch('player')
  onPlayerUpdated() {
    this.loginToken = this.player.token
  }

  // @ts-ignore
  beforeRouteEnter(to, from, next) {
    next((vm: PlayerView) => {
      vm.$apollo.queries.player.refetch().catch((err: any) => {
        gqlErrorHandler(vm, err)
      })
    })
  }

  get apollo(): Record<string, VueApolloQueryDefinition> {
    return {
      player: {
        update: data => data.player,
        query: require('@/graphql/player.gql'),
        variables(this: PlayerView) {
          return { playerID: playerModule.player.id }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.view-player {
  margin: 0 auto;
  .token-show {
    color: dodgerblue;
    font-size: 3rem;
    font-weight: bold;
  }
}
</style>
